/**
 * @Title: FileUtils.java
 * @Package com.lemon.utils.file
 * @Description: (一句话阐述):
 * @author Ran_cc
 * @date 2018年11月2日
 * @version V1.0
 */
package com.lemon.utils.file;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.lemon.conf.MyException;
import com.lemon.utils.StringUtil;

import net.coobird.thumbnailator.Thumbnails;

/**
 * <p>
 * Title: FileUtils
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author Ran_cc
 * @date 2018年11月2日
 * @版本 V 1.0
 */
public class FileUtils {

	private static final int FILE_SIZE = 1024; //1kb = 1024

	/**
	 * <b>Description:<blockquote> 把接受的全部文件打成压缩包
	 * </blockquote></b>
	 * 
	 * @Title: downloadZip
	 * @param file
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月3日
	 */
	public static HttpServletResponse downloadZip(File file , HttpServletResponse response) {
		try {
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");

			// 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
			response.setHeader("Content-Disposition" ,
					"attachment;filename=" + URLEncoder.encode(file.getName() , "UTF-8"));
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				File f = new File(file.getPath());
				f.delete();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return response;
	}

	/**
	 * <b>Description:<blockquote> 下载网络图片 , 不指定下载位置
	 * </blockquote></b>
	 * 
	 * @Title: downloadPicture
	 * @param urlList
	 * @param fileName //保存的文件名
	 * @author Ran_cc
	 * @date 2018年11月3日
	 */
	public static HttpServletResponse downloadPicture(String urlList , String fileName , HttpServletResponse response) {
		URL url = null;
		try {
			url = new URL(urlList);
			DataInputStream dataInputStream = new DataInputStream(url.openStream());
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			int length;

			// 设置输出的格式
			response.reset();
			response.setContentType("bin");
			response.addHeader("Content-Disposition" , "attachment;filename=" + URLEncoder.encode(fileName , "UTF-8"));
			// 循环取出流中的数据
			byte[] b = new byte[200];
			int len;

			while ((len = dataInputStream.read(b)) > 0) {
				response.getOutputStream().write(b , 0 , len);
			}
			dataInputStream.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}

	public static Map<String , Object> getImageInfo(String filePath) {

		long startTime = System.currentTimeMillis();
		Map<String , Object> imageInfoMap = new HashMap<>();
		InputStream is = null;
		try {
			File file = new File(filePath);
			is = new FileInputStream(file);
			BufferedImage image = ImageIO.read(is);
			imageInfoMap.put("size" , file.length());
			imageInfoMap.put("width" , image.getWidth());
			imageInfoMap.put("htight" , image.getHeight());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close(); // 关闭流
				} catch (IOException e) {
					System.out.println("getImageInfo I/O exception " + e.getMessage());
				}
			}
		}
		long endTime = System.currentTimeMillis();
		System.out.println("take time: " + (endTime - startTime));
		return imageInfoMap;
	}

	public static Map<String , Object> getImageInfo(File file) {

		long startTime = System.currentTimeMillis();
		Map<String , Object> imageInfoMap = new HashMap<>();
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			BufferedImage image = ImageIO.read(is);
			imageInfoMap.put("size" , file.length());
			imageInfoMap.put("width" , image.getWidth());
			imageInfoMap.put("htight" , image.getHeight());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close(); // 关闭流
				} catch (IOException e) {
					System.out.println("getImageInfo I/O exception " + e.getMessage());
				}
			}
		}
		long endTime = System.currentTimeMillis();
		System.out.println("take time: " + (endTime - startTime));
		return imageInfoMap;
	}

	public static File compressImage(File file) {
		try {
			Map<String , Object> map = getImageInfo(file);
			String a = map.get("size").toString();
			if (StringUtil.isNotBlank(a)) {
				int aa = Integer.parseInt(a);
				System.out.println(aa / (100 * FILE_SIZE));
				int siz = aa / (100 * FILE_SIZE); // kb
				float f = 1f;
				if (siz >= 5 && siz < 10) {
					f = 0.5f;
				} else if (siz >= 10 && siz < 20) { //600 - 1m
					f = 0.35f;
				} else if (siz >= 20 && siz < 40) { //600 - 1m
					f = 0.3f;
				} else if (siz >= 40) {
					f = 0.1f;
				}
				else {
					f = 0.2f;
				}
				String path = file.getAbsolutePath();
				Thumbnails.of(path).scale(1f).outputQuality(f).toFile(path);
				//file = new File(path);
			}

		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return file;
	}

}
